import { useModel, history } from "@umijs/max";
import { Tabs } from "antd";
import React, { useState, useEffect } from "react";

const customEventName = 'clickMenuEvent'
export const dispatchEvent = (data: { label: string, key: string }) => {
  const clickMenuEvent = new CustomEvent(customEventName, { detail: data });
  console.log(data, 'datadatadata')
  document.body.dispatchEvent(clickMenuEvent)
}

const historyPush = (url: string) => {
  history.push(url || '/')
}

const MyTabs = () => {
  const { clickMenuList, setClickMenuList } = useModel('clickMenu')
  const [activeKey, setActiveKey] = useState(clickMenuList[0]?.key);

  useEffect(() => {
    document.body.addEventListener(customEventName, (data) => {
      const newPanes = data.detail
      setClickMenuList(list => {
        if (newPanes.key) {
          setActiveKey(newPanes.key)
        }

        if (!newPanes || list.some(item => item.key === newPanes.key)) {
          return list
        }

        return [...list, newPanes]
      })
    })
  }, [])

  const onChange = (newActiveKey: string) => {
    historyPush(newActiveKey)
    setActiveKey(newActiveKey);
  };

  const remove = (targetKey: TargetKey) => {
    let newActiveKey = activeKey;
    let lastIndex = -1;
    clickMenuList.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = clickMenuList.filter((item) => item.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setClickMenuList(newPanes);
    historyPush(newActiveKey)
    setActiveKey(newActiveKey);
  };

  const onEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };

  return <Tabs
    hideAdd
    type="editable-card"
    onChange={onChange}
    activeKey={activeKey}
    onEdit={onEdit}
    items={clickMenuList}
  />
}
export default ({ children }) => {
  return <>
    <MyTabs></MyTabs>
    {children}
  </>
}